import json
import os

import requests

current_path = os.path.dirname(os.path.abspath(__file__))


def download_google_font_icons(data, path: str):
    new_path = os.path.join(current_path, path)

    for el in data:
        url = f"https://fonts.gstatic.com/s/i/short-term/release/materialsymbolsoutlined/{el['id']}/fill1/48px.svg"
        response = requests.get(url)

        if response.status_code != 200:
            print(
                f"🔴 Icon {el['scope']}/{el['id']} skipped because it does not exist in the source."
            )
            continue

        if not os.path.exists(f"{new_path}/{el['scope']}"):
            os.makedirs(f"{new_path}/{el['scope']}")

        with open(f"{new_path}/{el['scope']}/{el['id']}.svg", "wb") as f:
            f.write(response.content)
            print(f"✅ Icon {el['scope']}/{el['id']} downloaded successfully")


with open(os.path.join(current_path, "supported_icons.json"), "r") as f:
    data = json.load(f)

download_google_font_icons(
    data, "./../../../../../assets/icons/supported_selectable_icons"
)

with open(os.path.join(current_path, "supported_icons.dart"), "wb") as dart_file:
    dart_file.write(
        """// * DO NOT EDIT THIS FILE. 
// 
// To re-generate it, please check the python script under services/utils/icon_downloader

""".encode()
    )

    dart_file.write(
        "/// List of all the supported icons in the app. This list does not take into account app functionality icons, just the icons that are selectable to identificate some accounts, categories...\n".encode()
    )
    dart_file.write("List<Map<String, dynamic>> supportedIcons = ".encode())
    dart_file.write(str(data).encode())
    dart_file.write(";".encode())
